import threading
import socket
import json


class ConnectTcpServer:
    def __init__(self, target_ip, target_port, local_ip=None, local_port=None, async_receive=True):
        self.target_ip = target_ip
        self.target_port = target_port
        self.connected = False
        self.async_receive = async_receive
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if local_ip or local_port:
            self.client.bind((local_ip, local_port))

    def connect(self):
        self.connected = True
        self.client.connect((self.target_ip, self.target_port))
        if self.async_receive:
            threading.Thread(target=self._rcv_worker).start()

    def disconnect(self):
        self.client.close()
        self.connected = False

    def _rcv_worker(self):
        while self.connected:
            data = self.client.recv(4096)
            self.receive_async(data)

    def receive_sync(self):
        return self.client.recv(4096)

    def receive_async(self, data):
        pass

    def send(self, data):
        if isinstance(data, dict):
            send_data = json.dumps(data).encode('utf8')
        elif isinstance(data, str):
            send_data = data.encode('utf8')
        elif isinstance(data, bytes) or isinstance(data, bytearray):
            send_data = data
        else:
            raise Exception('数据类型：[%s]无效' % type(data))
        self.client.send(send_data)
